<template>
  <div class="module-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>模块管理</h3>
          <el-button type="primary" @click="handleAdd">新增自定义模块</el-button>
        </div>
      </template>

      <!-- 移除对oaModule的依赖，因为后端不返回这种数据结构 -->
      <!--
      <div class="module-notice" v-if="!oaModule">
        <el-alert
          title="温馨提示：可能是网络或其他原因未能请求到官网的模块数据，但不影响系统的正常使用。"
          type="warning"
          show-icon
          :closable="false"
        />
      </div>
      -->

      <el-table :data="sysModule" border v-loading="loading">
        <el-table-column prop="title" label="模块名称" align="center" />
        <el-table-column prop="name" label="模块所在目录">
          <template #default="scope">app/{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column prop="desc" label="功能描述" />
        <el-table-column label="类型" align="center">
          <template #default="scope">
            <span v-if="scope.row.type === 1" class="red">系统模块</span>
            <span v-else-if="scope.row.type === 2" class="blue">普通模块</span>
            <span v-else-if="scope.row.type === 3" class="green">自定义模块</span>
          </template>
        </el-table-column>
        <el-table-column label="开发者" align="center">
          <template #default="scope">
            <span v-if="scope.row.sourse === 1">勾股OA</span>
            <span v-else-if="scope.row.sourse === 2">第三方</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <span v-if="scope.row.status === -1" class="red">未安装</span>
            <span v-else-if="scope.row.status === 0" class="yellow">已卸载</span>
            <span v-else-if="scope.row.status === 1" class="green">正常</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <div v-if="scope.row.status === -1">
              <el-button size="small" @click="handleView(scope.row)">查看</el-button>
              <el-dropdown>
                <el-button size="small">
                  更多
                  <el-icon><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-if="scope.row.is_file === 0"
                      @click="handleDownload(scope.row)"
                    >
                      下载
                    </el-dropdown-item>
                    <el-dropdown-item v-else @click="handleInstall(scope.row)">
                      安装
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>

            <div v-else-if="scope.row.status === 0">
              <el-button size="small" @click="handleView(scope.row)">查看</el-button>
              <el-dropdown>
                <el-button size="small">
                  更多
                  <el-icon><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item v-if="scope.row.sourse === 2" @click="handleEdit(scope.row)">
                      编辑
                    </el-dropdown-item>
                    <el-dropdown-item @click="handleRestore(scope.row)">恢复</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>

            <div v-else-if="scope.row.status === 1">
              <div v-if="scope.row.type === 3">
                <el-button size="small" @click="handleView(scope.row)">查看</el-button>
                <el-dropdown>
                  <el-button size="small">
                    更多
                    <el-icon><ArrowDown /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="handleEdit(scope.row)">编辑</el-dropdown-item>
                      <el-dropdown-item @click="handleDelete(scope.row)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div v-else>
                <el-button size="small" @click="handleView(scope.row)">查看</el-button>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑模块对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form :model="moduleForm" :rules="moduleRules" ref="moduleFormRef" label-width="120px">
        <el-alert
          title="注意：自定义模块目录不能和已有的模块目录相同，尽量使用个性化的目录，防止后期可能与官网新推出模块的目录相同，引起升级不必要的麻烦。"
          type="warning"
          show-icon
          :closable="false"
        />

        <el-form-item label="模块名称" prop="title">
          <el-input v-model="moduleForm.title" placeholder="请输入模块名称" />
        </el-form-item>

        <el-form-item label="模块所在目录" prop="name">
          <el-input v-model="moduleForm.name" placeholder="请输入模块所在目录" />
        </el-form-item>

        <el-form-item label="模块描述">
          <el-input
            v-model="moduleForm.desc"
            type="textarea"
            :rows="3"
            placeholder="请输入模块描述，不能超过200个字"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitModule">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { ArrowDown } from '@element-plus/icons-vue'
  import { homeApi } from '@/api/home'
  import axios from 'axios'

  // 数据相关
  const sysModule = ref([])
  const loading = ref(false)

  // 对话框相关
  const dialogVisible = ref(false)
  const dialogTitle = ref('')
  const isEdit = ref(false)

  // 表单数据
  const moduleForm = reactive({
    id: 0,
    type: 3,
    sourse: 2,
    title: '',
    name: '',
    desc: '',
  })

  // 表单验证规则
  const moduleRules = {
    title: [{ required: true, message: '请输入模块名称', trigger: 'blur' }],
    name: [{ required: true, message: '请输入模块所在目录', trigger: 'blur' }],
  }

  // 表单引用
  const moduleFormRef = ref()

  // 获取模块列表
  const getModuleList = async () => {
    loading.value = true
    try {
      const res: any = await homeApi.getModuleList({ limit: 999 })
      // 修复：正确访问响应数据
      if (res.code === 0) {
        // 后端返回的是数组，直接赋值给sysModule
        sysModule.value = res.data || []
        // oaModule.value = res.data.oa || []
      } else {
        ElMessage.error(res.msg || '获取模块列表失败')
      }
    } catch (error) {
      ElMessage.error('获取模块列表失败')
    } finally {
      loading.value = false
    }
  }

  // 查看模块详情
  const handleView = (row: any) => {
    ElMessageBox.alert(
      `
    <p><strong>模块名称:</strong> ${row.title}</p>
    <p><strong>模块目录:</strong> app/${row.name}</p>
    <p><strong>功能描述:</strong> ${row.desc || '无'}</p>
    <p><strong>类型:</strong> ${row.type === 1 ? '系统模块' : row.type === 2 ? '普通模块' : '自定义模块'}</p>
    <p><strong>开发者:</strong> ${row.sourse === 1 ? '勾股OA' : '第三方'}</p>
    <p><strong>状态:</strong> ${row.status === -1 ? '未安装' : row.status === 0 ? '已卸载' : '正常'}</p>
  `,
      '查看模块',
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
      }
    )
  }

  // 处理下载
  const handleDownload = async (row: any) => {
    try {
      // 这里应该调用实际的下载API
      ElMessage.info('下载功能开发中...')
    } catch (error) {
      ElMessage.error('下载失败')
    }
  }

  // 处理安装
  const handleInstall = async (row: any) => {
    try {
      const res: any = await homeApi.installModule({ id: row.id })
      // 修复：正确访问响应数据
      if (res.code === 0) {
        ElMessage.success(res.msg || '安装成功')
        getModuleList()
      } else {
        ElMessage.error(res.msg || '安装失败')
      }
    } catch (error) {
      ElMessage.error('安装失败')
    }
  }

  // 处理恢复
  const handleRestore = async (row: any) => {
    try {
      const res: any = await homeApi.restoreModule({ id: row.id })
      // 修复：正确访问响应数据
      if (res.code === 0) {
        ElMessage.success(res.msg || '恢复成功')
        getModuleList()
      } else {
        ElMessage.error(res.msg || '恢复失败')
      }
    } catch (error) {
      ElMessage.error('恢复失败')
    }
  }

  // 处理编辑
  const handleEdit = (row: any) => {
    dialogTitle.value = '编辑模块'
    isEdit.value = true
    dialogVisible.value = true
    // 填充表单数据
    Object.assign(moduleForm, row)
  }

  // 处理删除
  const handleDelete = (row: any) => {
    ElMessageBox.confirm(`确定要删除模块【${row.title}】吗？删除后不可恢复！`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      try {
        const res: any = await homeApi.deleteModule({ id: row.id })
        // 修复：正确访问响应数据
        if (res.code === 0) {
          ElMessage.success(res.msg || '删除成功')
          getModuleList()
        } else {
          ElMessage.error(res.msg || '删除失败')
        }
      } catch (error) {
        ElMessage.error('删除失败')
      }
    })
  }

  // 处理演示查看
  const handleDemo = (row: any) => {
    ElMessageBox.alert(
      `
    <p><strong>模块名称:</strong> ${row.title}</p>
    <p><strong>模块目录:</strong> app/${row.name}</p>
    <p><strong>功能描述:</strong> ${row.desc || '无'}</p>
    <p><strong>类型:</strong> ${row.type === 1 ? '系统模块' : row.type === 2 ? '普通模块' : '自定义模块'}</p>
    <p><strong>开发者:</strong> ${row.sourse === 1 ? '勾股OA' : '第三方'}</p>
  `,
      '查看模块详情',
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
      }
    )
  }

  // 处理新增
  const handleAdd = () => {
    dialogTitle.value = '新增自定义模块'
    isEdit.value = false
    dialogVisible.value = true
    // 重置表单
    Object.assign(moduleForm, {
      id: 0,
      type: 3,
      sourse: 2,
      title: '',
      name: '',
      desc: '',
    })
  }

  // 提交模块表单
  const submitModule = () => {
    if (!moduleFormRef.value) return

    moduleFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          const res: any = await homeApi.saveModule(moduleForm)
          // 修复：正确访问响应数据
          if (res.code === 0) {
            ElMessage.success(`${isEdit.value ? '编辑' : '新增'}成功`)
            dialogVisible.value = false
            getModuleList()
          } else {
            ElMessage.error(res.msg || `${isEdit.value ? '编辑' : '新增'}失败`)
          }
        } catch (error) {
          ElMessage.error(`${isEdit.value ? '编辑' : '新增'}失败`)
        }
      }
    })
  }

  // 处理对话框关闭
  const handleDialogClose = () => {
    if (moduleFormRef.value) {
      moduleFormRef.value.resetFields()
    }
  }

  // 初始化加载
  onMounted(() => {
    getModuleList()
  })
</script>

<style scoped>
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .module-notice {
    margin-bottom: 20px;
  }

  .red {
    color: #f56c6c;
  }

  .blue {
    color: #409eff;
  }

  .green {
    color: #67c23a;
  }

  .yellow {
    color: #e6a23c;
  }
</style>
